<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>发帖</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<link href="../../../static/webapp/css/common.css" type="text/css" rel="stylesheet">
<link href="../../../static/webapp/css/function.css" type="text/css" rel="stylesheet">
<link href="../../../static/webapp/css/post.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="../../../static/webapp/js/common.js"></script>
<script type="text/javascript" src="../../../static/webapp/js/template.js"></script>
<script type="text/javascript" src="../../../static/webapp/js/tools.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
var projectName = '<?php echo $this->root_dir?>/';
var page = 1;
function loaded () {

}

/*加载贴子*/
function publish(){
    
}

function fileSelected() {
	var file = document.getElementById('upfile').files[0];
	if (file) {
	  var fileSize = 0;
	  if (file.size > 1024 * 1024)
		fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
	  else
		fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
	
	  var maxlen = $('.image-uploads li:visible').length;
	  if (maxlen >= 6) return false;
	  uploadFile()
	}
}

function uploadFile() {
	var fd = new FormData();
	fd.append("upfile", document.getElementById('upfile').files[0]);
	fd.append("_csrf", '<?php echo Yii::$app->request->csrfToken;?>');
	//fd.append("upfile", document.getElementById('upfile').files[0]);
	var xhr = new XMLHttpRequest();

	xhr.open("POST", "<?php echo $this->createUrl('/community/upload')?>", true);

	xhr.onloadstart = function(e){
		
    //$('.upload-progress').removeClass('uhide');
    $('.image-upload li:last').removeClass('upload').addClass('uploading');
}
	xhr.upload.addEventListener('progress', uploadProgress, false);
	xhr.addEventListener("load", uploadComplete, false);
	xhr.addEventListener("error", uploadFailed, false);
	xhr.addEventListener("abort", uploadCanceled, false);
	xhr.send(fd);
}

function uploadProgress(evt) {
	//Xalert(this.readyState);  
	//Xalert(evt.lengthComputable);
	if (evt.lengthComputable) {
	  var percentComplete = Math.round(evt.loaded * 100 / evt.total);
	  
	  $('#progressNumber').animate({
		  width: percentComplete+ '%'
	  }, function(){
		  setTimeout(function(){
			  $('#progressNumber').width(0);
		  },1000);
	  });
	  
}
else {
  //document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}

function uploadComplete(evt) {
  $('.upload-progress').addClass('uhide');
  $('.image-upload li:last').addClass('upload').removeClass('uploading');
  
  var data = jQuery.parseJSON(evt.target.responseText);
  var src = projectName+data.url.replace('../', '');
  
  var ext =/\.[^\.]+/.exec(src);
  //src = src.replace(ext, '_120'+ext);
  var li = $('.image-uploads li:first').clone().removeClass('uhide');
  li.css('background-image','url('+src+')').attr('src', src);
  li.appendTo('.image-uploads')
/* This event is raised when the server send back a response */
//alert(evt.target.responseText);
}

function uploadFailed(evt) {
	alert("There was an error attempting to upload the file.");
}

function uploadCanceled(evt) {
	alert("The upload has been canceled by the user or the browser dropped the connection.");
}


function remove_image(obj){
	 $(obj).parent().fadeOut(500,function(){
	   $(this).remove();
	 });
  
}




function submit_publich(){
	//alert('asxs');
   var subject = $('#subject').val();
   var content = $('#postcontent').val();
   var anonymous = isnull($('#anonymous:checked').val()) ? 0 : 1;
   if ($.trim(subject) == ''){
       Xalert('请输入帖子主题！', 1500);
       return false;
   }
  
   var image = [];
  
   $('.image-uploads li:visible').each(function(){
       var src = $(this).attr('src').replace(projectName, '');
       
       image.push(src);
    });
    if ($.trim(content) == '' && image.length == 0){
       Xalert('请输入帖子内容或上传图片！', 1500);
       return false;
   }
   alert(image.join(','))
    $.post('http://pvoice.chinamobo.com/function_php/api/index.php/community_post/index/create', {forumid:1,subject: subject, content: content, images: image.join(','), '_csrf': '<?php echo Yii::$app->request->csrfToken;?>'}, function(data){
        if(data.result == 1){
            Xalert('发布成功', 1500);

            //href('post_list.html, array("Post[forumid]": forumid;');

        }else{
			Xalert(data.msg, 500);
			setTimeout(function(){
				goback();
			},1000);
		}
        
    },'json');
}

function upload_images_show(t){
    var div = $('.post-publich-upload');
	var ishide = div.hasClass("uhide");
	if (ishide && t ==1){
		setTimeout(function(){
			div.removeClass('uhide');
		},250);
		$("input[name=checkbox-images]").attr('checked', true);
	}else if (t == 0){
		setTimeout(function(){
		    div.addClass('uhide');
		},250);
		$("input[name=checkbox-images]").attr('checked', false);
	}
	
	
}
</script>
</head>

<body class="bg-eeeeee">


<div id="header" style="position: static">
  <div class="ub-img5 btn-return" onClick="goback();"></div>
  <h1 onClick="location.reload();">发帖</h1>
  <a href="javascript:submit_publich();" class="btn-send uc-a1 tx-middle t-wh">发布</a> </div>
<div class="post-publich bg-fff">
  <div class="line-20 uinn">
    <input id="subject" placeholder="在此输入帖子主题(必填)" class="uh">
  </div>
  <div class=" border-t-eee">
    <textarea class="uh" id="postcontent" placeholder="说点什么呢..."></textarea>
  </div>
  <div class="uinn ub ub-ver">
    <div class="image-upload">
      <div class="image-uploads">
        <li class="ub-img4 uhide"> <a class="remove uc-a" href="javascript:;" onClick="remove_image(this);"><font class="ulev4">－</font></a> </li>
      </div>
      <li class="upload ub-img4 " onClick="$('#upfile').click()"><span class="uploading">
        <input type="file" id="upfile" onchange="fileSelected();" accept="image/*"/>
        </span></li>
    </div>
    <div class="uinn ulev-2 t-999" id="111">最多上传6张图片</div>
  </div>
</div>
<div class="circle"></div>
<script type="text/javascript" src="../../../static/webapp/js/iscroll-probe.js"></script> 
<script type="text/javascript" src="../../../static/webapp/js/jquery-1.10.2.min.js"></script> 
<script type="text/javascript" src="../../../static/webapp/js/iscroll-pull.js"></script> 
<script type="text/javascript" src="../../../static/webapp/js/jquery.cookie.js"></script> 
<script type="text/javascript" src="../../../static/webapp/js/touchy.js"></script> 
<script>
$(function(){
	$('#postcontent, #subject').focus(function(){
		upload_images_show(0);
	});
	

   wx.config({
    debug: false,
    appId: '<?php echo $signPackage["appid"]?>',
    timestamp: '<?php echo $signPackage["timestamp"]?>',
    nonceStr: '<?php echo $signPackage["noncestr"]?>',
    signature: '<?php echo $signPackage["signature"]?>',
      jsApiList: [
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'hideMenuItems',
        'showMenuItems',
        'hideAllNonBaseMenuItem',
        'showAllNonBaseMenuItem',
        'translateVoice',
        'startRecord',
        'stopRecord',
        'onRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'uploadVoice',
        'downloadVoice',
        'chooseImage',
        'previewImage',
        'uploadImage',
        'downloadImage',
        'getNetworkType',
        'openLocation',
        'getLocation',
        'hideOptionMenu',
        'showOptionMenu',
        'closeWindow',
        'scanQRCode',
        'chooseWXPay',
        'openProductSpecificView',
        'addCard',
        'chooseCard',
        'openCard'
      ]
  });

// 5 图片接口
  // 5.1 拍照、本地选图
  var images = {
    localId: [],
    serverId: []
  };
  $('#111').on('click', function () {
    wx.chooseImage({
      success: function (res) {
        images.localId = res.localIds;
        alert('已选择 ' + res.localIds.length + ' 张图片');
		if (images.localId.length == 0) {
		  alert('请先使用 chooseImage 接口选择图片');
		  return;
		}
		var i = 0, length = images.localId.length;
		images.serverId = [];
		function upload() {
		  wx.uploadImage({
			localId: images.localId[i],
			success: function (res) {
			  i++;
			  alert('已上传：' + i + '/' + length);
			  images.serverId.push(res.serverId);
			  if (i < length) {
				upload();
			  }
			},
			fail: function (res) {
			  alert(JSON.stringify(res));
			}
		  });
		}
		upload();
	
      }
    });
  });

  /*// 5.2 图片预览
  document.querySelector('#previewImage').onclick = function () {
    wx.previewImage({
      current: 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
      urls: [
        'http://img3.douban.com/view/photo/photo/public/p2152117150.jpg',
        'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
        'http://img3.douban.com/view/photo/photo/public/p2152134700.jpg'
      ]
    });
  };*/

  /* 5.3 上传图片
  document.querySelector('#uploadImage').onclick = function () {
    if (images.localId.length == 0) {
      alert('请先使用 chooseImage 接口选择图片');
      return;
    }
    var i = 0, length = images.localId.length;
    images.serverId = [];
    function upload() {
      wx.uploadImage({
        localId: images.localId[i],
        success: function (res) {
          i++;
          alert('已上传：' + i + '/' + length);
          images.serverId.push(res.serverId);
          if (i < length) {
            upload();
          }
        },
        fail: function (res) {
          alert(JSON.stringify(res));
        }
      });
    }
    upload();
  };*/

});
</script>
</body>
</html>